package com.crazy.practice.boot.listener;

import com.crazy.practice.boot.even.PropertiesChangeEven;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author panyonghui
 * @describe 配置变更事件监听器
 * @date 2023/4/13 15:12
 */
@Slf4j
@Component
public class PropertiesChangeListener implements ApplicationListener<PropertiesChangeEven>, ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * 配置刷新
     */
    @Autowired(required = false)
    private ContextRefresher contextRefresher;

    @Override
    public void onApplicationEvent(PropertiesChangeEven propertiesChangeEven) {
        log.info("通过实现ApplicationListener.onApplicationEvent监听配置变更");
        Map propertiesMap = propertiesChangeEven.getNewProperties();
        ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) applicationContext.getEnvironment();
        MutablePropertySources mutablePropertySources = configurableEnvironment.getPropertySources();
        mutablePropertySources.addFirst(new MapPropertySource("refreshProperties", propertiesMap));
        // 刷新配置项
        contextRefresher.refresh();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
